package cn.rose.test;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * java测试商户接口发送，可以参考此类进行修改或编写
 */
public class Copy_2_of_SendCpData {
	
	public static final String FILE_PATH = "D:\\javaworkspace\\test\\src\\cn\\uc\\util\\jiuyou.xml";//测试文件位置
//	public static final String FILE_PATH = "D:\\javaworkspace\\test\\src\\cn\\uc\\util\\example.xml";//测试文件位置
//	public static final String FILE_PATH = "D:\\javaworkspace\\test\\src\\cn\\uc\\util\\wuhantw.xml";//测试文件位置

	// 仅此修改如下三个参数 修改后发送即可 注：example.xml需要和本类放在同一目录下
//	public static final String URL = "http://221.238.17.191:6002/";// 发送数据目标主机，自行修改
//	public static final String SECRET = "您的密钥"; // 商家密钥，填写对应您的密钥，自行修改
//	public static final String CPID = "您的CPID"; // 商家ID，填写您对应的ID，自行修改
//	public static final String URL = "http://221.238.17.191:6002/";// 发送数据目标主机，自行修改
//	public static final String SECRET = "60ab24479370870a342ab0e2b9833860"; //商家密钥，填写对应您的密钥
//	public static final String CPID = "UC.TEST"; //商家ID，填写您对应的ID
	
	
	
	//本机测试地址
	public static final String URL = "http://s.uc.cn:8003/";// 发送数据目标主机，自行修改
	public static final String SECRET = "2b4fe65dbd2bf0eb6153e29c366083b9"; //商家密钥，填写对应您的密钥
	public static final String CPID = "tianwang001"; //商家ID，填写您对应的ID

	// 以下所有代码勿动，直接运行即可
	public static void main(String[] args) {
		String urlStr = URL;// 请求uc主机
		String secret = SECRET;// 商家密钥
		/* 设定post传递的必备参数 start */
		String cpid = CPID; // 商户编号
//		String content = new SendCpData().getXmlContent(); // 业务数据结构
		String content = "";
		try {
			content = new Copy_2_of_SendCpData().loadStringFromFile(new File(FILE_PATH),"UTF-8");// 业务数据结构
		} catch (IOException e2) {
			e2.printStackTrace();
		} 
		String sign = (encodingMD5(secret + cpid + content)).substring(0, 16);// 加密标识
//		System.out.println(sign);
		/* 设定post传递的必备参数 end */
		try {
			content = URLEncoder.encode(content, "UTF-8");// 转换content字符编码用于post请求传输
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			System.out.println("[EXCEPTION] [EncodingException_At_Content_Str]");
		}

		/* 拼凑参数字符串 */
		StringBuffer paramSb = new StringBuffer();
		paramSb.append("cpid=").append(cpid).append("&sign=").append(sign).append("&content=").append(content);

		// 发送请求
		String result = sendPost(urlStr, paramSb.toString());
		try {
			result = new String(result.getBytes(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			System.out.println("[EXCEPTION] [EncodingException_At_Result_Str]");
		}
		System.out.println(result);// 打印请求信息 此信息根据您的不同需求或进行解析显示

	}

	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1_JAVA)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			int count = 0;
			while ((line = in.readLine()) != null) {
				if (count == 0) {
					result += line;
				} else {
					result += "\n" + line;
				}
				count++;
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 读取xml文件 注：此xml文件要与本类放于同一目录下 字符编码UTF-8
	 * @return
	 */
	private String getXmlContent() {
		InputStream is = null;
		is = getClass().getResourceAsStream("111.xml");
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 一定要以UTF-8编码格式创建流来读取文件
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		StringBuffer sb = new StringBuffer();
		String temp = "";
		try {
			int count = 0;
			while ((temp = br.readLine()) != null) {
				if (count == 0) {
					sb.append(temp);
				} else {
					sb.append("\r\n").append(temp);
				}
				count++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();

	}

	/**
	 * MD5 加密
	 */
	private static String encodingMD5(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}
    /**
     * 从文件中读取文本内容
     * @param file 目标文件
     * @param encoding 目标文件的文本编码格式
     * @return
     * @throws IOException
     */
    public static String loadStringFromFile(File file, String encoding) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
            StringBuilder builder = new StringBuilder();
            char[] chars = new char[4096];
            int length = 0;
            while (0 < (length = reader.read(chars))) {
                builder.append(chars, 0, length);
            }
            return builder.toString();
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
